<script setup lang="ts">
import type { FormInstance, FormValidateCallback } from 'element-plus'
import type { EaTask } from './type'
import { tree2List } from '@/utils/list'

const baseApi = '/ea/ea-task'

defineProps<{
  // 禁用表单内的所有组件
  disabled?: boolean
  // 禁用属性列表（只读不可输入）
  disabledProps?: string[]
  // 不可见属性列表（忽略不加载）
  invisibleProps?: string[]
}>()

const emit = defineEmits<{
  (e: 'complete', id?: string, isNew?: boolean): void
  (e: 'submitting', submitting: boolean): void
}>()

const { initRelatedData, relatedData } = useOption({
  dict: ['task_fee_type', 'task_status'],
  load: {
    memberIdOptions: { type: 'IamMember', label: 'nickname' },
    workTypeIdOptions: {
      type: 'EaWorkType',
      label: 'title',
      parent: 'parentId',
      parentPath: 'parentIdsPath',
      lazyChild: false
    },
    orgIdOptions: { type: 'IamOrg', label: 'name', parent: 'parentId', parentPath: 'parentIdsPath', lazyChild: false },
    discountCouponUserIdOptions: { type: 'EaDiscountCouponUser', label: 'discountCouponId' }
  }
})

const { loadData, loading, model } = useDetail<EaTask>(baseApi, {
  peopleNum: 1,
  isPay: 0,
  isAssign: false,
  isInvoice: false
})

const { submitting, submit } = useForm({ baseApi, successCallback: (id, isNew) => emit('complete', id, isNew) })
watch(submitting, value => emit('submitting', value))

//  表单
const formRef = ref<FormInstance>()

const validate = (
  callback: FormValidateCallback = (valid: boolean) =>
    !valid && ElMessage.error({ message: '表单校验不通过', grouping: true })
) =>
  Promise.all([formRef.value].map(e => e?.validate?.(callback)).filter(e => !!e))
    .then((arr: (boolean | undefined)[]) => arr.every(e => e))
    .catch(() => false)

defineExpose({
  init: (id?: string, refresh = true, initData?: Record<string, unknown>) => {
    // 初始化选项
    initRelatedData()
    if (model.value.id === id && !refresh) return
    // 加载数据
    loadData(id).then(() => {
      if (!id) {
        if (initData) Object.keys(initData).forEach(key => (model.value[key as keyof EaTask] = initData[key] as any))
      }
    })
  },
  validate,
  getData: async (relatedLabel = false) => {
    const data: Record<string, unknown> = _.cloneDeep(model.value)
    if (!relatedLabel) return data
    if ((data.memberId as string)?.length) {
      const options = relatedData.memberIdOptions
      data.memberIdLabel = options.find(e => e.value === data.memberId)?.label
    } else data.memberIdLabel = undefined

    data.taskFeeTypeLabel = relatedData.taskFeeTypeOptions.find(e => e.value === data.taskFeeType)
    if ((data.workTypeId as string)?.length) {
      let options = relatedData.workTypeIdOptions
      options = tree2List(options)
      data.workTypeIdLabel = options.find(e => e.value === data.workTypeId)?.label
    } else data.workTypeIdLabel = undefined
    if ((data.orgId as string)?.length) {
      let options = relatedData.orgIdOptions
      options = tree2List(options)
      data.orgIdLabel = options.find(e => e.value === data.orgId)?.label
    } else data.orgIdLabel = undefined

    data.taskStatusLabel = relatedData.taskStatusOptions.find(e => e.value === data.taskStatus)
    if ((data.discountCouponUserId as string)?.length) {
      const options = relatedData.discountCouponUserIdOptions
      data.discountCouponUserIdLabel = options.find(e => e.value === data.discountCouponUserId)?.label
    } else data.discountCouponUserIdLabel = undefined

    return data
  },
  submit: () => submit(model.value, formRef.value),
  reset: () => {
    formRef.value?.resetFields()
    model.value.id = void 0
  }
})
</script>

<template>
  <el-form ref="formRef" v-loading="loading" :model="model" label-width="90px" :disabled="disabled">
    <el-row :gutter="18">
      <el-col v-if="!invisibleProps?.includes('memberId')" :span="12">
        <el-form-item prop="memberId" label="客户id">
          <el-select v-model="model.memberId" :disabled="disabledProps?.includes('memberId')" filterable clearable>
            <el-option v-for="item in relatedData.memberIdOptions" :key="item.value" v-bind="item">
              <div v-if="typeof item.ext === 'string'" class="option">
                {{ item.label }}
                <span class="ext">（{{ item.ext }}）</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('peopleNum')" :span="12">
        <el-form-item prop="peopleNum" label="工作人数">
          <el-input-number v-model="model.peopleNum" :disabled="disabledProps?.includes('peopleNum')" step-strictly />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('longitude')" :span="12">
        <el-form-item prop="longitude" label="经度">
          <el-input-number v-model="model.longitude" :disabled="disabledProps?.includes('longitude')" :precision="2" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('latitude')" :span="12">
        <el-form-item prop="latitude" label="纬度">
          <el-input-number v-model="model.latitude" :disabled="disabledProps?.includes('latitude')" :precision="2" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workAddress')" :span="12">
        <el-form-item prop="workAddress" label="地址">
          <el-input v-model="model.workAddress" :disabled="disabledProps?.includes('workAddress')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('taskFeeType')" :span="12">
        <el-form-item prop="taskFeeType" label="收费模式">
          <el-select
            v-model="model.taskFeeType"
            :disabled="disabledProps?.includes('taskFeeType')"
            filterable
            clearable
          >
            <el-option v-for="item in relatedData.taskFeeTypeOptions" :key="item.value" v-bind="item" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workHour')" :span="12">
        <el-form-item prop="workHour" label="工时" :rules="{ required: true, message: '不能为空' }">
          <el-input-number v-model="model.workHour" :disabled="disabledProps?.includes('workHour')" :precision="0" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('price')" :span="12">
        <el-form-item prop="price" label="费用">
          <el-input-number v-model="model.price" :disabled="disabledProps?.includes('price')" :precision="2" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('payMoney')" :span="12">
        <el-form-item prop="payMoney" label="支付金额">
          <el-input-number v-model="model.payMoney" :disabled="disabledProps?.includes('payMoney')" :precision="2" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workDemand')" :span="12">
        <el-form-item prop="workDemand" label="工作要求">
          <el-input v-model="model.workDemand" :disabled="disabledProps?.includes('workDemand')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('taskPic')" :span="12">
        <el-form-item
          prop="taskPic"
          label="发布任务图片"
          :rules="{ required: true, message: '不能为空', whitespace: true }"
        >
          <el-input
            v-model="model.taskPic"
            :disabled="disabledProps?.includes('taskPic')"
            clearable
            type="textarea"
            autosize
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workTypeId')" :span="12">
        <el-form-item prop="workTypeId" label="工种">
          <el-tree-select
            v-model="model.workTypeId"
            :disabled="disabledProps?.includes('workTypeId')"
            :data="relatedData.workTypeIdOptions"
            filterable
            default-expand-all
            check-strictly
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('areaCode')" :span="12">
        <el-form-item prop="areaCode" label="地区编号">
          <el-input v-model="model.areaCode" :disabled="disabledProps?.includes('areaCode')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('orgId')" :span="12">
        <el-form-item prop="orgId" label="区域id">
          <el-tree-select
            v-model="model.orgId"
            :disabled="disabledProps?.includes('orgId')"
            :data="relatedData.orgIdOptions"
            filterable
            default-expand-all
            check-strictly
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('taskStatus')" :span="12">
        <el-form-item prop="taskStatus" label="任务状态">
          <el-select v-model="model.taskStatus" :disabled="disabledProps?.includes('taskStatus')" filterable clearable>
            <el-option v-for="item in relatedData.taskStatusOptions" :key="item.value" v-bind="item" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('completeTime')" :span="12">
        <el-form-item prop="completeTime" label="完成时间">
          <el-date-picker
            v-model="model.completeTime"
            :disabled="disabledProps?.includes('completeTime')"
            clearable
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('isPay')" :span="12">
        <el-form-item prop="isPay" label="是否支付">
          <el-input-number v-model="model.isPay" :disabled="disabledProps?.includes('isPay')" step-strictly />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('discountCouponUserId')" :span="12">
        <el-form-item prop="discountCouponUserId" label="优惠券用户ID">
          <el-select
            v-model="model.discountCouponUserId"
            :disabled="disabledProps?.includes('discountCouponUserId')"
            filterable
            clearable
          >
            <el-option v-for="item in relatedData.discountCouponUserIdOptions" :key="item.value" v-bind="item">
              <div v-if="typeof item.ext === 'string'" class="option">
                {{ item.label }}
                <span class="ext">（{{ item.ext }}）</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('detailAddress')" :span="12">
        <el-form-item prop="detailAddress" label="详细地址">
          <el-input v-model="model.detailAddress" :disabled="disabledProps?.includes('detailAddress')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('appointmentTime')" :span="12">
        <el-form-item prop="appointmentTime" label="预约时间">
          <el-date-picker
            v-model="model.appointmentTime"
            :disabled="disabledProps?.includes('appointmentTime')"
            clearable
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('workTypeName')" :span="12">
        <el-form-item prop="workTypeName" label="其他工种名称">
          <el-input v-model="model.workTypeName" :disabled="disabledProps?.includes('workTypeName')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('taskVideo')" :span="12">
        <el-form-item prop="taskVideo" label="发布任务视频">
          <el-input v-model="model.taskVideo" :disabled="disabledProps?.includes('taskVideo')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('payType')" :span="12">
        <el-form-item prop="payType" label="支付方式">
          <el-input v-model="model.payType" :disabled="disabledProps?.includes('payType')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('orderNo')" :span="12">
        <el-form-item prop="orderNo" label="订单编号">
          <el-input v-model="model.orderNo" :disabled="disabledProps?.includes('orderNo')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('isAssign')" :span="12">
        <el-form-item prop="isAssign" label="是否指派单">
          <el-switch v-model="model.isAssign" :disabled="disabledProps?.includes('isAssign')" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('assignWorkerId')" :span="12">
        <el-form-item prop="assignWorkerId" label="指派工人Id">
          <el-input v-model="model.assignWorkerId" :disabled="disabledProps?.includes('assignWorkerId')" clearable />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('totalPrice')" :span="12">
        <el-form-item prop="totalPrice" label="总价">
          <el-input-number
            v-model="model.totalPrice"
            :disabled="disabledProps?.includes('totalPrice')"
            :precision="2"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('isInvoice')" :span="12">
        <el-form-item prop="isInvoice" label="是否开票">
          <el-switch v-model="model.isInvoice" :disabled="disabledProps?.includes('isInvoice')" />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('raisePrice')" :span="12">
        <el-form-item prop="raisePrice" label="加价">
          <el-input-number
            v-model="model.raisePrice"
            :disabled="disabledProps?.includes('raisePrice')"
            :precision="2"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('singlePrice')" :span="12">
        <el-form-item prop="singlePrice" label="单人总价">
          <el-input-number
            v-model="model.singlePrice"
            :disabled="disabledProps?.includes('singlePrice')"
            :precision="2"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!invisibleProps?.includes('cityCode')" :span="12">
        <el-form-item prop="cityCode" label="城市编号">
          <el-input v-model="model.cityCode" :disabled="disabledProps?.includes('cityCode')" clearable />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
